<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="序号"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="姓名"
        prop="name"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('ammeterNo')"
      >
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="密码"
        prop="password"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('ammeterName')"
      >
        <template slot-scope="{row}">
          <span>{{ row.password }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="角色"
        prop="role"
        sortable="custom"
        align="center"
        width="120"
      >
        <template slot-scope="{row}">
          <span>{{ row.role|role }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="权限"
        prop="permissionName"
        sortable="custom"
        align="center"
        width="120"
        :class-name="getSortClass('mRoom')"
      >
        <template slot-scope="{row}">
          <span>{{ row.permissionName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group
            v-for="item in [
              {id:1,name:'普通人员'} ,
              {id:2,name:'管理员'},
              {id:3,name:'集团人员'},
            ]"
            :key="item.id"
            v-model="temp.role"
          >
            <el-radio-button :label="item.id">{{ item.name }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限" prop="perms">
          <el-radio-group v-for="item in permsList" :key="item.id" v-model="temp.perms">
            <el-radio-button :label="item.id">{{ item.name }}</el-radio-button>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { service2 as http } from '@/utils/request'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    role(type) {
      const name = [0,
        '普通人员',
        '管理员',
        '集团人员']
      return name[type]
    }
  },
  data() {
    const validateNormal = (rule, value, callback) => {
      if (value.length < 0) {
        callback(new Error('不能为空'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      nameList: [],
      permsList: [],
      commitRules: {
        name: [{ required: true, trigger: 'blur', validator: validateNormal }],
        password: [{ required: true, trigger: 'blur', validator: validateNormal }]
      },
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        password: '',
        perms: -1,
        role: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '需要姓名信息', trigger: 'blur' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        password: [{ required: true, message: '需要填写密码', trigger: 'blur' }]
      },
      downloadLoading: false

    }
  },
  created() {
    this.getList()
    http({
      url: '/org/getFactory',
      method: 'get'
    }).then(res => {
      this.permsList = res.list
      this.permsList.push({ id: -1, name: '全部' })
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      http({
        url: '/user/userList',
        method: 'get'
      }).then(res => {
        // console.info('res', res)
        this.list = res.list
        this.nameList = []
        this.list.map((item) => this.nameList.push(item.name))

        // this.total = 30
        this.listLoading = false
      })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        password: '',
        perms: -1,
        role: 1
      }
    },
    handleCreate() {
      this.ammeterNoDis = false
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (this.nameList.indexOf(this.temp.name.trim()) != -1) {
          this.$notify({
            title: '警告',
            message: '重复的名字',
            type: 'warning',
            duration: 2000
          })
          return
        }
        if (valid) {
          http({
            url: '/user/saveUser',
            method: 'post',
            params: { ...this.temp }
          }).then(res => {
            if (res.code != 1) {
              this.$notify({
                title: 'error',
                message: '联系管理员',
                type: 'warning',
                duration: 2000
              })
              return
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'ok',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.ammeterNoDis = true
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          http({
            url: '/user/updateUser',
            method: 'post',
            params: { ...this.temp }
          }).then(res => {
            if (res.code != 1) {
              this.$notify({
                title: '警告',
                message: '重复的姓名',
                type: 'error',
                duration: 2000
              })
              return
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'ok',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
